package center

import (
	"fmt"
)

//LRU-K算法
type List struct {
	max_len uint32
	cur_len uint32
	head    *Element
	trail   *Element
}
type Element struct {
	//pre  interface{}
	next *Element
	data interface{}
}

//从head 淘汰
func (l *List) insert_to_trail(e *Element) {
	if l.cur_len < l.max_len { //未满
		if l.trail != nil {
			l.trail.next = e
			l.trail = e
		} else {
			l.trail = e
			l.head = e
			fmt.Println("插入缓存队列第一个数据:", e)
		}
		l.cur_len++
		fmt.Println("插入了一个数据:", e, "当前队列大小为:", l.cur_len, "/", l.max_len)

	} else { //已满
		head := l.head
		l.head = head.next
		fmt.Println("缓存已满:", l.cur_len, "/", l.max_len, "淘汰了队头的数据:", head)
		head.next = nil
		l.cur_len--
		l.insert_to_trail(e)
	}
}
func (l *List) get_element(key interface{}) *Element {

	if l.head == nil {
		fmt.Println("缓存队列未初始化")
		return nil
	}
	var cur_e *Element = l.head
	var pre *Element
	for {
		val, ok := cur_e.data.(*User_info)
		if ok == true {
			if key == val.user_id {
				return cur_e
			} else {
				pre = cur_e
				cur_e = cur_e.next
				if cur_e == nil {
					fmt.Println("数据不在缓存队列中")
					break
				}
			}
		} else {
			fmt.Println("缓存队列中的数据类型有错误")
			break
		}

	}
	if cur_e != nil { //调遣到尾部
		if pre != nil {
			pre.next = cur_e.next
		}
		cur_e.next = nil
		user_List.insert_to_trail(cur_e)
	}
	return cur_e
}
func (l *List) get_element_bycode(key string) *Element {
	if l.head == nil {
		fmt.Println("缓存队列未初始化")
		return nil
	}
	var cur_e *Element = l.head
	var pre *Element
	for {
		val, ok := cur_e.data.(*User_info)
		if ok == true {
			if key == val.user_code {
				return cur_e
			} else {
				pre = cur_e
				cur_e = cur_e.next
				if cur_e == nil {
					fmt.Println("数据不在缓存队列中")
					break
				}
			}
		} else {
			fmt.Println("缓存队列中的数据类型有错误")
			break
		}
	}
	if cur_e != nil { //调遣到尾部
		if pre != nil {
			pre.next = cur_e.next
		}
		cur_e.next = nil
		user_List.insert_to_trail(cur_e)
	}
	return cur_e
}
